package com.atguigu.spzx.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.constant.UserInfoSexEnum;
import com.atguigu.spzx.common.constant.UserInfoStatusEnum;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.result.ResultCodeEnum;
import com.atguigu.spzx.common.utils.AuthContextUtil;
import com.atguigu.spzx.common.utils.BeanUtils;
import com.atguigu.spzx.common.utils.UUIDUtils;
import com.atguigu.spzx.common.constant.RedisKeyConstant;
import com.atguigu.spzx.common.entity.UserInfo;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import com.atguigu.spzx.user.vo.UserInfoRespVo;
import com.atguigu.spzx.user.vo.UserLoginReqVo;
import com.atguigu.spzx.user.vo.UserRegisterReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * UserInfoServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2023/11/5
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 用户注册
     * @param vo
     */
    @Override
    public void register(UserRegisterReqVo vo) {
        //验证码校验
        String redisCode = redisTemplate.opsForValue().get(RedisKeyConstant.USER_REGISTER_PHONE_PREFIX + vo.getUsername());
        if (!redisCode.equals(vo.getCode())) {
            throw new GuiguException(ResultCodeEnum.VALIDATE_CODE_ERROR);
        }

        //校验用户名不能重复
        if (userInfoMapper.getUserInfoByUserName(vo.getUsername()) != null) {
            throw new GuiguException(ResultCodeEnum.USERNAME_IS_EXISTS_ERROR);
        }

        //保存用户信息到数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(vo.getUsername());
        userInfo.setNickName(vo.getNickName());
        userInfo.setPassword(DigestUtils.md5DigestAsHex(vo.getPassword().getBytes()));
        userInfo.setPhone(vo.getUsername());
        userInfo.setStatus(UserInfoStatusEnum.NORMAL.getCode());
        userInfo.setSex(UserInfoSexEnum.MAN.getCode());
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.insert(userInfo);

        //从redis删除验证码
        redisTemplate.delete(RedisKeyConstant.USER_REGISTER_PHONE_PREFIX + vo.getUsername());
    }

    /**
     * 会员登录
     * @param vo
     * @return
     */
    @Override
    public String login(UserLoginReqVo vo) {
        //根据用户名查询用户信息
        UserInfo userInfo = userInfoMapper.getUserInfoByUserName(vo.getUsername());
        if (userInfo == null) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }

        //比对密码
        String dbPassword = userInfo.getPassword();
        String inputPassword = vo.getPassword();
        if (!dbPassword.equals(DigestUtils.md5DigestAsHex(inputPassword.getBytes()))) {
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }

        //校验用户被禁用
        if (UserInfoStatusEnum.STOP.getCode().equals(userInfo.getStatus())) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }

        //生成token
        String token = UUIDUtils.getSimpleUUID();

        //保存用户信息到redis
        redisTemplate.opsForValue().set(RedisKeyConstant.USER_LOGIN_TOKEN_PREFIX + token,
                JSON.toJSONString(userInfo),
                RedisKeyConstant.USER_LOGIN_TOKEN_EXPIRE,
                TimeUnit.DAYS);
        return token;
    }

    /**
     * 获取当前登录用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfoRespVo getCurrentUserInfo(String token) {
        //从redis获取用户信息
//        String userInfoJsonStr = redisTemplate.opsForValue().get(RedisKeyConstant.USER_LOGIN_TOKEN_PREFIX + token);
//        if (StrUtil.isBlank(userInfoJsonStr)) {
//            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
//        }
//        UserInfo userInfo = JSON.parseObject(userInfoJsonStr, UserInfo.class);
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserInfoRespVo userInfoRespVo = BeanUtils.toBean(userInfo, UserInfoRespVo.class);
        return userInfoRespVo;
    }
}
